﻿/*----------------------------------------------------------------
// Copyright (C) 梦幻天堂
// 版权所有。 
//
// 文件名：DecryptEncrypt.cs
// 文件功能描述：加密解密类 包括对称加密/解密、CRC效验、MD5无逆向编码 无法还原、Base64 UUEncoded 编码 支持还原、DES 加密 支持Key(钥匙)加密变化 支持还原
//
// 
// 创建标识：田银
// 创建时间：2011/11/7
//
//修改标识：
//修改描述：
//
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Security;
using System.Runtime.InteropServices;

namespace LYM.CommonWeb.DecryptEncrypt
{
    /// <summary>
    /// AES加密解密
    /// </summary>
    public class EncryptUtil
    {
        private static readonly string AESKEY = "4123567812345678";//16或者32位   

        //private static readonly string DESKEY = ConfigurationManager.AppSettings["DESKEY"].Trim();   
        private static readonly string DESKEY = "PORG56JK";//8位   

        /// <summary>   
        /// AES加密   
        /// </summary>   
        /// <param name="data">要加密的字符串</param>   
        /// <returns>加密后的字符串</returns>   
        public static string EncryptAES(string data)
        {
            try
            {
                RijndaelManaged aes = new RijndaelManaged();
                byte[] bData = UTF8Encoding.UTF8.GetBytes(data);
                aes.Key = UTF8Encoding.UTF8.GetBytes(AESKEY);
                aes.IV = UTF8Encoding.UTF8.GetBytes(AESKEY);
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                ICryptoTransform iCryptoTransform = aes.CreateEncryptor();
                byte[] bResult = iCryptoTransform.TransformFinalBlock(bData, 0, bData.Length);

                // return Convert.ToBase64String(bResult); //返回base64加密;   
                return ByteToHex(bResult);                //返回十六进制数据;   
            }
            catch
            {
                throw;
            }
        }

        /// <summary>   
        /// AES加密   
        /// </summary>   
        /// <param name="data">要加密的字符串</param>   
        /// <param name="sKey">密钥串（16位或32位）</param>   
        /// <returns>加密后的字符串</returns>   
        public static string EncryptAES(string data, string sKey)
        {
            try
            {
                RijndaelManaged aes = new RijndaelManaged();
                byte[] bData = UTF8Encoding.UTF8.GetBytes(data);
                aes.Key = UTF8Encoding.UTF8.GetBytes(sKey);
                aes.IV = UTF8Encoding.UTF8.GetBytes(sKey);
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                ICryptoTransform iCryptoTransform = aes.CreateEncryptor();
                byte[] bResult = iCryptoTransform.TransformFinalBlock(bData, 0, bData.Length);

                // return Convert.ToBase64String(bResult); //返回base64加密;   
                return ByteToHex(bResult);                //返回十六进制数据;   
            }
            catch
            {
                throw;
            }
        }

        /// <summary>   
        /// AES解密   
        /// </summary>   
        /// <param name="data">要解密的字符串</param>   
        /// <returns>解密后的字符串</returns>   
        public static string DecryptAES(string data)
        {
            try
            {
                RijndaelManaged aes = new RijndaelManaged();
                //byte[] bData = Convert.FromBase64String(data); //解密base64;   
                byte[] bData = HexToByte(data);                  //16进制to byte[];   
                aes.Key = UTF8Encoding.UTF8.GetBytes(AESKEY);
                aes.IV = UTF8Encoding.UTF8.GetBytes(AESKEY);
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                ICryptoTransform iCryptoTransform = aes.CreateDecryptor();
                byte[] bResult = iCryptoTransform.TransformFinalBlock(bData, 0, bData.Length);
                return Encoding.UTF8.GetString(bResult);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>   
        /// AES解密   
        /// </summary>   
        /// <param name="data">要解密的字符串</param>   
        /// <param name="sKey">密钥串（16位或32位字符串）</param>   
        /// <returns>解密后的字符串</returns>   
        public static string DecryptAES(string data, string sKey)
        {
            try
            {
                RijndaelManaged aes = new RijndaelManaged();
                //byte[] bData = Convert.FromBase64String(data); //解密base64;   
                byte[] bData = HexToByte(data);                  //16进制to byte[];   
                aes.Key = UTF8Encoding.UTF8.GetBytes(sKey);
                aes.IV = UTF8Encoding.UTF8.GetBytes(sKey);
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                ICryptoTransform iCryptoTransform = aes.CreateDecryptor();
                byte[] bResult = iCryptoTransform.TransformFinalBlock(bData, 0, bData.Length);
                return Encoding.UTF8.GetString(bResult);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>   
        /// DES加密   
        /// </summary>   
        /// <param name="data">要加密的字符串</param>   
        /// <returns>加密后的字符串</returns>   
        public static string EncryptDES(string data)
        {
            DES des = new DESCryptoServiceProvider();
            des.Mode = CipherMode.ECB;
            des.Key = Encoding.UTF8.GetBytes(DESKEY);
            des.IV = Encoding.UTF8.GetBytes(DESKEY);

            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] resultBytes = des.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);

            //return Convert.ToBase64String(resultBytes); //密文以base64返回;(可根据实际需要返回16进制数据;)   
            return ByteToHex(resultBytes);//十六位   
        }

        /// <summary>   
        /// DES加密   
        /// </summary>   
        /// <param name="data">要加密的字符串</param>   
        /// <param name="key">密钥串（8位字符串）</param>   
        /// <returns>加密后的字符串</returns>   
        public static string EncryptDES(string data, string key)
        {
            DES des = new DESCryptoServiceProvider();
            des.Mode = CipherMode.ECB;
            des.Key = Encoding.UTF8.GetBytes(key);
            des.IV = Encoding.UTF8.GetBytes(key);

            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] resultBytes = des.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);

            //return Convert.ToBase64String(resultBytes); //密文以base64返回;(可根据实际需要返回16进制数据;)   
            return ByteToHex(resultBytes);//十六位   
        }

        /// <summary>   
        /// DES解密   
        /// </summary>   
        /// <param name="data">要解密的字符串</param>   
        /// <param name="key">密钥串（8位字符串）</param>   
        /// <returns>解密后的字符串</returns>   
        public static string DecryptDES(string data)
        {
            DES des = new DESCryptoServiceProvider();
            des.Mode = CipherMode.ECB;
            des.Key = Encoding.UTF8.GetBytes(DESKEY);
            des.IV = Encoding.UTF8.GetBytes(DESKEY);

            //byte[] bytes = Convert.FromBase64String(data);   
            byte[] bytes = HexToByte(data);
            byte[] resultBytes = des.CreateDecryptor().TransformFinalBlock(bytes, 0, bytes.Length);

            return Encoding.UTF8.GetString(resultBytes);
        }

        /// <summary>   
        /// DES解密   
        /// </summary>   
        /// <param name="data">要解密的字符串</param>   
        /// <param name="key">密钥串（8位字符串）</param>   
        /// <returns>解密后的字符串</returns>   
        public static string DecryptDES(string data, string key)
        {
            DES des = new DESCryptoServiceProvider();
            des.Mode = CipherMode.ECB;
            des.Key = Encoding.UTF8.GetBytes(key);
            des.IV = Encoding.UTF8.GetBytes(key);

            //byte[] bytes = Convert.FromBase64String(data);   
            byte[] bytes = HexToByte(data);
            byte[] resultBytes = des.CreateDecryptor().TransformFinalBlock(bytes, 0, bytes.Length);

            return Encoding.UTF8.GetString(resultBytes);
        }

        // method to convert hex string into a byte array     
        private static byte[] HexToByte(string data)
        {
            data = data.Replace(" ", "");

            byte[] comBuffer = new byte[data.Length / 2];

            for (int i = 0; i < data.Length; i += 2)
                comBuffer[i / 2] = (byte)Convert.ToByte(data.Substring(i, 2), 16);

            return comBuffer;
        }

        // method to convert a byte array into a hex string     
        private static string ByteToHex(byte[] comByte)
        {
            StringBuilder builder = new StringBuilder(comByte.Length * 3);

            foreach (byte data in comByte)
                builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));

            return builder.ToString().ToUpper().Replace(" ", "");
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">要加密的串</param>
        /// <param name="code">16 16位加密,32 32位加密</param>
        /// <returns></returns>
        public static string MD5(string str, int code)
        {
            str = str.ToLower();
            if (code == 16) //16位MD5加密（取32位加密的9~25字符） 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
            }

            if (code == 32) //32位加密 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
            }

            return "00000000000000000000000000000000";
        }
    }

    /// <summary>
    /// DecryptEncrypt 的摘要说明
    /// 作用：实现对称加密、解密
    /// </summary>
    public class DecryptEncrypt
    {
        private static SymmetricAlgorithm mobjCryptoService;
        private static string Key;

        public DecryptEncrypt()
        {
            mobjCryptoService = new RijndaelManaged();
            Key = "rrp(%&h70x89H$jgsfgfsI0456Ftma81&fvHrr&&76*h%(12lJ$lhj!y6&(*jkPer44a";
        }

        #region 获得密钥
        /**/
        /// <summary>
        /// 获得密钥
        /// </summary>
        /// <returns>密钥</returns>
        private static byte[] GetLegalKey()
        {
            string _TempKey = Key;
            mobjCryptoService.GenerateKey();
            byte[] bytTemp = mobjCryptoService.Key;
            int KeyLength = bytTemp.Length;
            if (_TempKey.Length > KeyLength)
                _TempKey = _TempKey.Substring(0, KeyLength);
            else if (_TempKey.Length < KeyLength)
                _TempKey = _TempKey.PadRight(KeyLength, ' ');
            return ASCIIEncoding.ASCII.GetBytes(_TempKey);
        }
        #endregion

        #region 获得初始向量
        /// <summary>
        /// 获得初始向量IV
        /// </summary>
        /// <returns>初试向量IV</returns>
        private static byte[] GetLegalIV()
        {
            string _TempIV = "@afetj*Ghg7!rNIfsgr95GUqd9gsrb#GG7HBh(urjj6HJ($jhWk7&!hjjri%$hjk";
            mobjCryptoService.GenerateIV();
            byte[] bytTemp = mobjCryptoService.IV;
            int IVLength = bytTemp.Length;
            if (_TempIV.Length > IVLength)
                _TempIV = _TempIV.Substring(0, IVLength);
            else if (_TempIV.Length < IVLength)
                _TempIV = _TempIV.PadRight(IVLength, ' ');
            return ASCIIEncoding.ASCII.GetBytes(_TempIV);
        }
        #endregion

        #region 加密方法
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="Source">待加密的串</param>
        /// <returns>经过加密的串</returns>
        public static string Encrypto(string Source)
        {
            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
            MemoryStream ms = new MemoryStream();
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            //创建对称加密器对象
            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
            //定义将数据流链接到加密转换的流
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            ms.Close();
            byte[] bytOut = ms.ToArray();
            return Convert.ToBase64String(bytOut);
        }

        #endregion

        #region 解密方法
        /**/
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="Source">待解密的串</param>
        /// <returns>经过解密的串</returns>
        public static string Decrypto(string Source)
        {
            byte[] bytIn = Convert.FromBase64String(Source);
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            //创建对称解密器对象
            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
            //定义将数据流链接到加密转换的流
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }
        #endregion

    }

    /**/
    /// <summary>
    /// CRC 效验
    /// 快速检测算法
    /// </summary>
    public class CRC32Encrypt
    {

        protected static ulong[] crc32Table;

        /**/
        /// <summary>
        /// 构造：初始化效验表
        /// </summary>
        public CRC32Encrypt()
        {
            const ulong ulPolynomial = 0xEDB88320;
            ulong dwCrc;
            crc32Table = new ulong[256];
            int i, j;
            for (i = 0; i < 256; i++)
            {
                dwCrc = (ulong)i;
                for (j = 8; j > 0; j--)
                {
                    if ((dwCrc & 1) == 1)
                        dwCrc = (dwCrc >> 1) ^ ulPolynomial;
                    else
                        dwCrc >>= 1;
                }
                crc32Table[i] = dwCrc;
            }
        }

        /**/
        /// <summary>
        /// 字节数组效验
        /// </summary>
        /// <param name="buffer">ref 字节数组</param>
        /// <returns></returns>
        public static ulong ByteCRC(ref byte[] buffer)
        {
            ulong ulCRC = 0xffffffff;
            ulong len;
            len = (ulong)buffer.Length;
            for (ulong buffptr = 0; buffptr < len; buffptr++)
            {
                ulong tabPtr = ulCRC & 0xFF;
                tabPtr = tabPtr ^ buffer[buffptr];
                ulCRC = ulCRC >> 8;
                ulCRC = ulCRC ^ crc32Table[tabPtr];
            }
            return ulCRC ^ 0xffffffff;
        }


        /**/
        /// <summary>
        /// 字符串效验
        /// </summary>
        /// <param name="sInputString">字符串</param>
        /// <returns></returns>
        public static ulong StringCRC(string sInputString)
        {
            byte[] buffer = Encoding.Default.GetBytes(sInputString);
            return ByteCRC(ref buffer);
        }

        /**/
        /// <summary>
        /// 文件效验
        /// </summary>
        /// <param name="sInputFilename">输入文件</param>
        /// <returns></returns>
        public static ulong FileCRC(string sInputFilename)
        {
            FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] bInput = new byte[inFile.Length];
            inFile.Read(bInput, 0, bInput.Length);
            inFile.Close();

            return ByteCRC(ref bInput);
        }

    }
    /**/
    /// <summary>
    /// MD5 无逆向编码
    /// 获取唯一特征串，可用于密码加密
    /// (无法还原)
    /// </summary>
    public class MD5Encrypt
    {

        public MD5Encrypt()
        {
        }

        /**/
        /// <summary>
        /// 获取字符串的特征串
        /// </summary>
        /// <param name="sInputString">输入文本</param>
        /// <returns></returns>
        public static string HashString(string sInputString)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(sInputString))).Replace("-", "");
            return encoded;
        }

        /**/
        /// <summary>
        /// 获取文件的特征串
        /// </summary>
        /// <param name="sInputFilename">输入文件</param>
        /// <returns></returns>
        public static string HashFile(string sInputFilename)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] bInput = new byte[inFile.Length];
            inFile.Read(bInput, 0, bInput.Length);
            inFile.Close();

            string encoded = BitConverter.ToString(md5.ComputeHash(bInput)).Replace("-", "");
            return encoded;
        }

    }

    /**/
    /// <summary>
    /// Base64 UUEncoded 编码
    /// 将二进制编码为ASCII文本，用于网络传输
    /// (可还原)
    /// </summary>
    public class BASE64Encrypt
    {

        public BASE64Encrypt()
        {
        }

        /**/
        /// <summary>
        /// 解码字符串
        /// </summary>
        /// <param name="sInputString">输入文本</param>
        /// <returns></returns>
        public static string DecryptString(string sInputString)
        {
            char[] sInput = sInputString.ToCharArray();
            try
            {
                byte[] bOutput = System.Convert.FromBase64String(sInputString);
                return Encoding.Default.GetString(bOutput);
            }
            catch (System.ArgumentNullException)
            {
                //base 64 字符数组为null
                return "";
            }
            catch (System.FormatException)
            {
                //长度错误，无法整除4
                return "";
            }
        }

        /**/
        /// <summary>
        /// 编码字符串
        /// </summary>
        /// <param name="sInputString">输入文本</param>
        /// <returns></returns>
        public static string EncryptString(string sInputString)
        {
            byte[] bInput = Encoding.Default.GetBytes(sInputString);
            try
            {
                return System.Convert.ToBase64String(bInput, 0, bInput.Length);
            }
            catch (System.ArgumentNullException)
            {
                //二进制数组为NULL.
                return "";
            }
            catch (System.ArgumentOutOfRangeException)
            {
                //长度不够
                return "";
            }
        }

        /**/
        /// <summary>
        /// 解码文件
        /// </summary>
        /// <param name="sInputFilename">输入文件</param>
        /// <param name="sOutputFilename">输出文件</param>
        public static void DecryptFile(string sInputFilename, string sOutputFilename)
        {
            System.IO.StreamReader inFile;
            char[] base64CharArray;

            try
            {
                inFile = new System.IO.StreamReader(sInputFilename,
                  System.Text.Encoding.ASCII);
                base64CharArray = new char[inFile.BaseStream.Length];
                inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length);
                inFile.Close();
            }
            catch
            {//(System.Exception exp) {
                return;
            }

            // 转换Base64 UUEncoded为二进制输出
            byte[] binaryData;
            try
            {
                binaryData =
                  System.Convert.FromBase64CharArray(base64CharArray,
                  0,
                  base64CharArray.Length);
            }
            catch (System.ArgumentNullException)
            {
                //base 64 字符数组为null
                return;
            }
            catch (System.FormatException)
            {
                //长度错误，无法整除4
                return;
            }

            // 写输出数据
            System.IO.FileStream outFile;
            try
            {
                outFile = new System.IO.FileStream(sOutputFilename,
                  System.IO.FileMode.Create,
                  System.IO.FileAccess.Write);
                outFile.Write(binaryData, 0, binaryData.Length);
                outFile.Close();
            }
            catch
            {// (System.Exception exp) {
                //流错误
            }

        }

        /**/
        /// <summary>
        /// 编码文件
        /// </summary>
        /// <param name="sInputFilename">输入文件</param>
        /// <param name="sOutputFilename">输出文件</param>
        public static void EncryptFile(string sInputFilename, string sOutputFilename)
        {

            System.IO.FileStream inFile;
            byte[] binaryData;

            try
            {
                inFile = new System.IO.FileStream(sInputFilename,
                  System.IO.FileMode.Open,
                  System.IO.FileAccess.Read);
                binaryData = new Byte[inFile.Length];
                long bytesRead = inFile.Read(binaryData, 0,
                  (int)inFile.Length);
                inFile.Close();
            }
            catch
            { //(System.Exception exp) {
                return;
            }

            // 转换二进制输入为Base64 UUEncoded输出
            // 每3个字节在源数据里作为4个字节 
            long arrayLength = (long)((4.0d / 3.0d) * binaryData.Length);

            // 如果无法整除4
            if (arrayLength % 4 != 0)
            {
                arrayLength += 4 - arrayLength % 4;
            }

            char[] base64CharArray = new char[arrayLength];
            try
            {
                System.Convert.ToBase64CharArray(binaryData,
                  0,
                  binaryData.Length,
                  base64CharArray,
                  0);
            }
            catch (System.ArgumentNullException)
            {
                //二进制数组为NULL.
                return;
            }
            catch (System.ArgumentOutOfRangeException)
            {
                //长度不够
                return;
            }

            // 写UUEncoded数据到文件内
            System.IO.StreamWriter outFile;
            try
            {
                outFile = new System.IO.StreamWriter(sOutputFilename,
                  false,
                  System.Text.Encoding.ASCII);
                outFile.Write(base64CharArray);
                outFile.Close();
            }
            catch
            {// (System.Exception exp) {
                //文件流出错
            }


        }
    }
    /**/
    /// <summary>
    /// DES 加密
    /// 支持Key(钥匙)加密变化
    /// 支持还原
    /// 
    /// 演示操作：
    ///  // 64位，8个字节
    ///  string sSecretKey;
    ///
    ///  // 获取Key
    ///  sSecretKey = GenerateKey();
    ///
    ///  // 托管
    ///  GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
    ///
    ///  // 加密文件
    ///  EncryptFile(@"C:\MyData.txt",
    ///  @"C:\Encrypted.txt",
    ///  sSecretKey);
    ///
    ///  // 解密文件
    ///  DecryptFile(@"C:\Encrypted.txt",
    ///  @"C:\Decrypted.txt",
    ///  sSecretKey);
    ///
    ///  // 释放托管内容
    ///  ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
    ///  gch.Free();
    /// </summary>
    public class DESEncrypt
    {
        [DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
        public static extern bool ZeroMemory(IntPtr Destination, int Length);

        public DESEncrypt()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /**/
        /// <summary>
        /// 创建Key
        /// </summary>
        /// <returns></returns>
        public static string GenerateKey()
        {
            // 创建一个DES 算法的实例。自动产生Key
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

            // 返回自动创建的Key 用于加密
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }

        /**/
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="sInputString">输入字符</param>
        /// <param name="sKey">Key</param>
        /// <returns>加密结果</returns>
        public static string EncryptString(string sInputString, string sKey)
        {
            byte[] data = Encoding.Default.GetBytes(sInputString);
            byte[] result;
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            result = desencrypt.TransformFinalBlock(data, 0, data.Length);

            string desString = "";
            for (int i = 0; i < result.Length; i++)
            {
                desString += result[i].ToString() + "-";
            }

            //return desString.TrimEnd('-');
            return BitConverter.ToString(result);
        }

        /**/
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="sInputString">输入字符</param>
        /// <param name="sKey">Key</param>
        /// <returns>解密结果</returns>
        public static string DecryptString(string sInputString, string sKey)
        {
            string[] sInput = sInputString.Split("-".ToCharArray());
            byte[] data = new byte[sInput.Length];
            byte[] result;
            for (int i = 0; i < sInput.Length; i++)
                data[i] = byte.Parse(sInput[i], System.Globalization.NumberStyles.HexNumber);

            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateDecryptor();
            result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return Encoding.Default.GetString(result);
        }

        /**/
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="sInputFilename">输入文件</param>
        /// <param name="sOutputFilename">输出文件</param>
        /// <param name="sKey">Key</param>
        public static void EncryptFile(string sInputFilename,
          string sOutputFilename,
          string sKey)
        {
            FileStream fsInput = new FileStream(sInputFilename,
              FileMode.Open,
              FileAccess.Read);

            FileStream fsEncrypted = new FileStream(sOutputFilename,
              FileMode.Create,
              FileAccess.Write);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsEncrypted,
              desencrypt,
              CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();
        }

        /**/
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="sInputFilename">输入文件</param>
        /// <param name="sOutputFilename">输出文件</param>
        /// <param name="sKey">Key</param>
        public static void DecryptFile(string sInputFilename,
          string sOutputFilename,
          string sKey)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            FileStream fsread = new FileStream(sInputFilename,
              FileMode.Open,
              FileAccess.Read);
            ICryptoTransform desdecrypt = DES.CreateDecryptor();
            CryptoStream cryptostreamDecr = new CryptoStream(fsread,
              desdecrypt,
              CryptoStreamMode.Read);
            StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
            fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
            fsDecrypted.Flush();
            fsDecrypted.Close();
        }

        #region ========加密========

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "lym");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "lym");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion
    }
}
